﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcMovie.Models;
using MvcMovie.Repositories;
using System.Web.Security;
using MvcMovie.Filters;

namespace MvcMovie.Controllers
{
    public class AuthenticatorController : Controller
    {
        //
        // GET: /Authenticator/

        public ActionResult Login()
        {
            return View();
        }

        [Log(Message = "User Login")]
        public ActionResult Entrar(User user)
        {
            var repositoryLocal = new UserRepository();
            try
            {
                var userLocal = repositoryLocal.GetByUsername(user.Username);
                if (!user.password.Equals(userLocal.password))
                    return RedirectToAction("Login");
            }
            catch (NullReferenceException)
            {
                return RedirectToAction("Login");
            }

            //Session["User"] = user;
            FormsAuthentication.SetAuthCookie(user.Username, false);
            return RedirectToAction("Index", "HelloWorld");
        }

        [Log(Message = "User Logout")]
        public ActionResult Sair()
        {
            //Session.Abandon();
            FormsAuthentication.SignOut();
            return RedirectToAction("Login");
        }

        [Log(Message = "User Creation")]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(User user)
        {
            var repositoryLocal = new UserRepository();

            try
            {
                repositoryLocal.GetByUsername(user.Username);
                return View();
            }
            catch (NullReferenceException)
            {
                repositoryLocal.AddUser(user);
            }

            return RedirectToAction("Login");
        }

    }
}
